//
//  LocalPersistent.m
//  SmartContorary
//
//  Created by enghou on 17/7/8.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//[{account:11,pwd:11,data:{}},{},{}]

#import "LocalPersistent.h"
#import "FMDB.h"
#import "NSDate+ToString.h"
static LocalPersistent *m = nil;
@implementation LocalPersistent{
    FMDatabase *db;
}

+(instancetype)sharedInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        m = [[LocalPersistent alloc]init];
        NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentDirectory = [path   objectAtIndex:0];
        NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"test.db"];
        NSLog(@"dbPath= %@",dbPath);
        /*连接数据库——连接数据库，并没有创建数据库文件，直到打开成功才算真正创建*/
        FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
        m->db = db;
        if ([db open]) {
            NSString *sqlCreateTable = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT, '%@' TEXT,'%@' DATETIME)",@"Users",@"uid",@"account",@"pwd",@"lastLoginTime"];
            BOOL res = [db executeUpdate:sqlCreateTable];
            if (!res) {
                NSLog(@"%@",[db lastError]);
            }
            [db close];
        }
    });
    return m;
}

-(void)delAllUser{
    if ([db open]) {
        NSString *sql = @"delete from Users";
        BOOL result = [db executeUpdate:sql];
        NSLog(@"%i",result);
    }
}

-(void)latestLoginUser:(NSString **)usr passWord:(NSString **)p{
    if ([db open]) {
        NSString *sql = @"select * from Users order by lastLoginTime desc";
        FMResultSet *set = [db executeQuery:sql];
        while ([set next]) {
            if (usr) {
                NSString *account = [set stringForColumn:@"account"];
                *usr = account;
            }
            if (p) {
                NSString *pwd = [set stringForColumn:@"pwd"];
                *p = pwd;
            }
            return;
        }
    }
}

-(void)savePwdForAccount:(NSString *)account pwd:(NSString *)pwd{
    if ([db open]) {
        NSString *query = [NSString stringWithFormat:@"select count(account) from Users where account = '%@'",account];
        FMResultSet *rs = [db executeQuery:query];
        BOOL exists = NO;
        if([rs next]){
            int totalCount = [rs intForColumnIndex:0];
            if (totalCount > 0) {
                exists = YES;
            }
        }
        NSString *sql;
        if (exists) {
            NSDate *date = [NSDate date];
            NSString *dateStr = [date dateLineStr];
            sql = [NSString stringWithFormat:@"UPDATE Users SET pwd = '%@',lastLoginTime = '%@' where account = '%@'",pwd,dateStr,account];
            BOOL result = [db executeUpdate:sql];
            if (!result) {
                NSLog(@"更新失败!");
            }
        }else{
            NSDate *date = [NSDate date];
            NSString *dateStr = [date dateLineStr];
            sql = [NSString stringWithFormat:@"insert into Users (account,pwd,lastLoginTime) values ('%@','%@','%@')",account,pwd,dateStr];
            BOOL result = [db executeUpdate:sql];
            if (!result) {
                NSLog(@"插入失败!");
            }
        }
    }
}

-(NSString *)passWordForAccount:(NSString *)account{
    if ([db open]) {
        NSString *sql = [NSString stringWithFormat:@"select pwd from User where account = '%@'",account];
        FMResultSet *set = [db executeQuery:sql];
        while ([set next]) {
            NSString *pwd = [set stringForColumnIndex:0];
            return pwd;
        }
        return nil;
    }
    return nil;
}

-(void)removeContentForKey:(NSString *)key{
    if (key) {
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:key];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
}

-(void)saveContent:(id)cnt forKey:(NSString *)key{
    if ( key) {
        [[NSUserDefaults standardUserDefaults]setValue:cnt forKey:key];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
}

-(id)contentForKey:(NSString *)key{
    return [[NSUserDefaults standardUserDefaults]valueForKey:key];
}
@end
